package com.xyf.sys.controller;

import cn.hutool.core.lang.Validator;
import com.alibaba.fastjson2.JSONObject;
import com.xyf.sys.config.CustomException;
import com.xyf.sys.config.MiniprogramConfig;
import com.xyf.sys.constant.CommonConstant;
import com.xyf.sys.domain.Role;
import com.xyf.sys.domain.User;
import com.xyf.sys.mapper.UserMapper;
import com.xyf.sys.service.*;
import com.xyf.sys.util.WechatHttpUtil;
import com.xyf.sys.util.R;
import com.xyf.sys.vo.LoginUser;
import com.xyf.sys.vo.QrcodeParam;
import com.xyf.sys.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Base64;
import java.util.List;
import java.util.Random;

/**
 * @Author
 * @Date
 * @Description
 */
@RestController
@RequestMapping
@Slf4j
@Api(tags = "登录相关")
public class LoginController {

    @Autowired
    private IUserService userService;
    @Autowired
    @Qualifier(value = "clientConfig")
    private MiniprogramConfig.MiniConfig clientConfig;
    @Autowired
    @Qualifier(value = "manageConfig")
    private MiniprogramConfig.MiniConfig manageConfig;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IWechatService wechatService;
    @Autowired
    private IUserLogisticService userLogisticService;
    @Autowired
    private IDeliveryService deliveryService;
    @Autowired
    private ISysPriceSchemeService priceSchemeService;
    @Autowired
    private IUserRoleService roleService;

    @ApiOperation("login")
    @PostMapping("/login")
    public Object login(@RequestBody LoginUser loginUser, HttpServletRequest request) {
        String openid = loginUser.getUserId();
        String headerOpenid = request.getHeader("OPENID");
        String appId = request.getHeader("APPID");
        if (StringUtils.isNotBlank(headerOpenid)) {
            if (Validator.isMobile(headerOpenid)){
                User user = userService.getByMobile(headerOpenid, appId);
                headerOpenid = user.getId();
            }
            openid = headerOpenid;
        }
        String unionid = null;
        if (StringUtils.isBlank(openid)) {
            String secret = appId.equals(clientConfig.getAppid()) ? clientConfig.getSecret() : manageConfig.getSecret();
            String data = WechatHttpUtil.getOpenId(appId, loginUser.getCode(), secret);
            log.info("login data{} ", data);
            JSONObject jsonObject = JSONObject.parseObject(data);
            openid = jsonObject.getString("openid");
            unionid = jsonObject.getString("unionid");
        }
        User user = userService.getUser(openid);
        if (user == null) {
            user = userService.create(openid, unionid, appId);
        } else if (StringUtils.isNotBlank(unionid) && StringUtils.isBlank(user.getUnionid())){
            user.setUnionid(unionid);
            user.setAppid(appId);
            userService.save(user);
        }
        if (StringUtils.isBlank(user.getAppid())){
            user.setAppid(appId);
            userService.save(user);
        }
        if (StringUtils.isBlank(user.getAvatar())){
            user.setAvatar(CommonConstant.randomAvatorList.get(new Random().nextInt(CommonConstant.randomAvatorList.size())));
            userService.save(user);
        }
        if (StringUtils.isNotBlank(loginUser.getMobile()) && Validator.isMobile(loginUser.getMobile())){
            User talent = userService.getByMobile(loginUser.getMobile());
            user.setDeptId(talent.getDeptId());
            userService.save(user);
        }
        if (user.getDeptId() == null){
            user.setClient(clientConfig.getAppid().equals(request.getHeader("APPID")));
            user.setDeptId(181L);
            user.setUserId(user.getId());
            userService.update(user);
        }
        UserVo userInfo = userService.getInfo(user.getId(), appId.equals(clientConfig.getAppid()));
        if (StringUtils.isNotBlank(user.getUnionid())){
            User serviceUser = userService.getUser(user.getUnionid(), manageConfig.getAppid());
            if (serviceUser != null && serviceUser.getDeptId() != null){
                List<Role> roleList = roleService.getRoleList(user.getId(), user.getDeptId());
                if (roleList.stream().filter(role -> "REGIMENT".equalsIgnoreCase(role.getRoleKey()) || "GUIDE".equalsIgnoreCase(role.getRoleKey())).findAny().isPresent()) {
                    UserVo manager = userService.getInfo(serviceUser.getId(), false, true);
                    userInfo.setManagerUser(manager);
                }
            }
        }
        return R.ok(userInfo);
    }

    @ApiOperation("获取用户手机号")
    @PostMapping("/getNumber")
    public R getPhoneNumber(@RequestBody LoginUser loginUser, HttpServletRequest request) throws Exception {
        String appId = request.getHeader("APPID");
        String secret = appId.equals(clientConfig.getAppid()) ? clientConfig.getSecret() : manageConfig.getSecret();
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + wechatService.getAccessToken(appId, secret);
        JSONObject body = new JSONObject();
        body.put("code", loginUser.getCode());
        byte[] bytes = WechatHttpUtil.doWechatPost(url, body);
        JSONObject jsonObject = JSONObject.parseObject(new String(bytes, "UTF-8"));
        if (jsonObject.getInteger("errcode") == 0) {
            JSONObject phoneInfo = jsonObject.getJSONObject("phone_info");
            String phoneNumber = phoneInfo.getString("phoneNumber");
            User user = userService.get(loginUser.getUserId());
            if (user != null) {
                user.setMobile(phoneNumber);
                userMapper.updateByPrimaryKeySelective(user);
            }
            return R.ok(phoneNumber);
        } else {
            throw new CustomException(jsonObject.getString("errmsg"));
        }
    }


    @ApiOperation("生成二维码")
    @PostMapping("/qrcode")
    public R qrcode(@RequestBody QrcodeParam qrcodeParam, HttpServletRequest request) {
        String appid = qrcodeParam.getAppid();
        if (StringUtils.isBlank(appid)){
            appid = request.getHeader("APPID");
        }
        String eneSimulate = request.getHeader("ENV-Simulate");
        String secret = appid.equals(clientConfig.getAppid()) ? clientConfig.getSecret() : manageConfig.getSecret();
        String accessToken = wechatService.getAccessToken(appid, secret);
        JSONObject lineColor = new JSONObject();
        lineColor.put("g", 0);
        lineColor.put("b", 0);
        if ("release".equals(eneSimulate)) {
            lineColor.put("r", 0);
        } else {
            lineColor.put("r", 255);
        }
        JSONObject body = new JSONObject();
        body.put("page", qrcodeParam.getPage());
        body.put("check_path", "release".equals(eneSimulate));
        body.put("env_version", eneSimulate);
        body.put("line_color", lineColor);
        body.put("auto_color", false);
        body.put("scene", qrcodeParam.getScene());
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
        byte[] bytes = WechatHttpUtil.doWechatPost(url, body);
        return R.ok(Base64.getEncoder().encodeToString(bytes));
    }
}
